<template>
  <div class="direction-overview">
    <el-row :gutter="20">
      <el-col :span="24">
        <div ref="pieChartRef" class="chart-container"></div>
      </el-col>
    </el-row>
    
    <!-- 方向选择和学生列表区域 -->
    <el-row :gutter="20" class="mt20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>学生详情</span>
              <el-select
                v-model="selectedDirection"
                placeholder="请选择方向"
                clearable
                style="width: 200px"
                @change="handleDirectionChange"
              >
                <el-option
                  v-for="item in directionList"
                  :key="item.id"
                  :label="item.directionName"
                  :value="item.id"
                />
              </el-select>
            </div>
          </template>
          
          <el-table v-loading="tableLoading" :data="filteredStudentList" style="width: 100%">
            <el-table-column label="姓名" align="center" prop="realname" width="100" />
            <el-table-column label="学号" align="center" prop="stuCode" width="120" />
            <el-table-column label="方向" align="center" prop="directionId" width="120">
              <template #default="scope">
                {{ getDirectionName(scope.row.directionId) }}
              </template>
            </el-table-column>
             <el-table-column label="总分" align="center" prop="totalScore" width="100">
              <template #default="scope">
                {{ calculateStudentTotalScore(scope.row) }}
              </template>
            </el-table-column>
             </el-table>
          
          <pagination
            v-show="totalStudents > 0"
            :total="totalStudents"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            @pagination="handlePagination"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from "vue";
import * as echarts from "echarts";
import { listStudent } from "@/api/infomanagement/student";
import Pagination from "@/components/Pagination/index.vue";

// 定义props
const props = defineProps({
  logList: {
    type: Array,
    default: () => [],
  },
  directionList: {
    type: Array,
    default: () => [],
  },
});

// 定义emits
const emit = defineEmits(['pagination']);

// 图表实例
const pieChartRef = ref(null);
let pieChartInstance = null;

// 方向统计数据
const directionStats = ref([]);

// 学生数据
const studentData = ref([]);

// 表格相关数据
const selectedDirection = ref(null);
const tableLoading = ref(false);
const filteredStudentList = ref([]);
const totalStudents = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
});

// 获取学生数据
const fetchStudentData = async () => {
  try {
    // 获取所有学生数据
    const res = await listStudent({});
    if (res.code === 200) {
      studentData.value = res.rows || [];
    }
  } catch (error) {
    console.error("获取学生数据失败:", error);
  }
};

// 计算方向统计数据
const calculateDirectionStats = () => {
  // 初始化统计数据结构
  // 第一层：按direction字段对数据进行方向维度的区分
  const statsByDirection = {};

  // 初始化每个方向的数据结构
  props.directionList.forEach((direction) => {
    statsByDirection[direction.id] = {
      directionId: direction.id,
      directionName: direction.directionName,
      studentCount: 0,
      students: new Set(), // 使用Set来统计不重复的学生
    };
  });

  // 根据学生数据统计各方向学生人数
  studentData.value.forEach((student) => {
    if (!student.directionId) return;

    if (!statsByDirection[student.directionId]) {
      // 如果方向不在列表中，跳过
      return;
    }

    // 添加学生到Set中
    const studentKey = `${student.studentNumber}-${student.studentName}`;
    statsByDirection[student.directionId].students.add(studentKey);
  });

  // 转换为数组并按方向ID排序
  const sortedDirections = Object.values(statsByDirection).sort(
    (a, b) => a.directionId - b.directionId
  );

  // 计算学生人数，并转换为表格所需格式
  const result = sortedDirections.map((item) => {
    const studentCount = item.students.size;

    return {
      directionId: item.directionId,
      directionName: item.directionName,
      studentCount,
    };
  });

  directionStats.value = result;
  return result;
};

// 获取方向名称
const getDirectionName = (id) => {
  if (!id) return '无方向';
  const direction = props.directionList.find(d => d.id === id);
  return direction ? direction.directionName : '未知方向';
};

// 计算学生的总分
const calculateStudentTotalScore = (student) => {
  if (!props.logList || props.logList.length === 0) return 0;
  
  // 根据学生的学号和姓名找到对应的日志记录
  const studentLogs = props.logList.filter(log => 
    log.studentNumber === student.stuCode && 
    log.studentName === student.realname
  );
  
  // 计算总分
  const totalScore = studentLogs.reduce((sum, log) => {
    // 确保分数是数字类型
    const score = Number(log.score) || 0;
    return sum + score;
  }, 0);
  
  return totalScore;
};

// 过滤学生数据
const filterStudentData = () => {
  let filtered = studentData.value;
  
  // 根据选择的方向过滤
  if (selectedDirection.value) {
    filtered = filtered.filter(student => student.directionId === selectedDirection.value);
  }
  
  // 更新总数
  totalStudents.value = filtered.length;
  
  // 分页处理
  const start = (queryParams.value.pageNum - 1) * queryParams.value.pageSize;
  const end = start + queryParams.value.pageSize;
  filteredStudentList.value = filtered.slice(start, end);
};

// 处理方向选择变化
const handleDirectionChange = () => {
  queryParams.value.pageNum = 1;
  filterStudentData();
};

// 处理分页
const handlePagination = (newParams) => {
  queryParams.value.pageNum = newParams.pageNum;
  queryParams.value.pageSize = newParams.pageSize;
  filterStudentData();
  emit('pagination', newParams);
};

// 初始化饼图
const initPieChart = () => {
  if (pieChartRef.value) {
    pieChartInstance = echarts.init(pieChartRef.value);
    updatePieChart();
  }
};

// 更新饼图
const updatePieChart = () => {
  if (!pieChartInstance) return;

  const stats =
    directionStats.value.length > 0 ? directionStats.value : calculateDirectionStats();

  // 准备饼图数据
  const pieData = stats.map((item) => ({
    name: item.directionName,
    value: item.studentCount,
  }));

  const option = {
    title: {
      text: "各方向学生人数分布",
      left: "center",
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)",
    },
    legend: {
      orient: "vertical",
      left: "left",
    },
    series: [
      {
        name: "学生人数",
        type: "pie",
        radius: "50%",
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };

  pieChartInstance.setOption(option, true);
};

// 调整图表大小
const resizeChart = () => {
  if (pieChartInstance) {
    pieChartInstance.resize();
  }
};

// 暴露方法给父组件
defineExpose({
  resizeChart,
});

// 组件挂载时初始化
onMounted(async () => {
  await fetchStudentData();
  calculateDirectionStats();
  filterStudentData(); // 初始化表格数据
  initPieChart();
  window.addEventListener("resize", resizeChart);
});

// 监听数据变化，更新图表
watch(
  () => [props.directionList, studentData.value, props.logList],
  async () => {
    // 如果学生数据为空，重新获取
    if (studentData.value.length === 0) {
      await fetchStudentData();
    }
    nextTick(() => {
      calculateDirectionStats();
      filterStudentData(); // 更新表格数据
      updatePieChart();
    });
  },
  { deep: true }
);
</script>

<style scoped>
.direction-overview {
  width: 100%;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mt20 {
  margin-top: 20px;
}
</style>
